﻿using IOT4Week1Day1.App;
using IOT4Week1Day1.App.Dtos;
using IOT4Week1Day1.Domain.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using CSRedis;  //redis的客户端
using Common;

namespace IOT4Week1Day1.ApiHost.Controllers
{
    [Route("api/[controller]/[action]")]  //配置路由
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly IUserAppService _userAppService;

        private readonly CSRedisClient _redis; //redis的客户端对象

        public LoginController(IUserAppService userAppService)
        {
            _userAppService = userAppService;
            
            _redis = new CSRedisClient("127.0.0.1:6379,password=123456"); //配置redis的连接字符串
            RedisHelper.Initialization(_redis);
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login(LoginDto input)
        {
            //模型验证
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            //1. 用户输入的验证码与redis缓存中的验证码进行比较
            string strCode = _redis.Get(input.CaptchaKey);

            if (!input.CaptchaCode.Equals(strCode))
            {
                return Ok(new { msg = "验证码无效", result = -1 });
            }

            //2. 查询用户输入的账号密码在数据库中是否存在
            //调用
            User user = _userAppService.Login(input);
            if (user != null)
            {
                return Ok(new { msg = "登录成功", result = 1, data = user });
            }

            return Ok(new { msg = "登录失败", result = 0 });

        }

        /// <summary>
        /// 获取图片验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetVCode(string captchaKey)
        {
            //1. 生成图片验证码（用到帮助类）
            ValidateCodeHelper helper = new ValidateCodeHelper();

            var ms = helper.Create(out string code, 5); //生成图片验证码，5位的

            //2. 设置到redis缓存（并设置有效期）
            _redis.Set(captchaKey, code, 5 * 60);// 缓存到redis数据库，5分钟过期

            //3. 返回图片
            return File(ms.ToArray(), "image/png");
        }
    }
}
